import React, {Component} from 'react';
import {Card, DatePicker, Form, Input, Modal, Select, TreeSelect, Upload} from 'antd';
import {PageContainer} from '@ant-design/pro-layout';
import './index.less';
// import {FormattedMessage} from "umi";
// import {formatMessage} from "@@/plugin-locale/localeExports";
import {connect, Dispatch} from 'umi';
// import {Dispatch} from "@@/plugin-dva/connect";

// import {PlusOutlined} from "@ant-design/icons/lib";
import {formatMessage, FormattedMessage} from "@@/plugin-locale/localeExports";
import {PlusOutlined} from '@ant-design/icons';

const treeData = [
  {
    title: 'Node1',
    value: '0-0',
    children: [
      {
        title: 'Child Node1',
        value: '0-0-1',
      },
      {
        title: 'Child Node2',
        value: '0-0-2',
      },
    ],
  },
  {
    title: 'Node2',
    value: '0-1',
  },
];
const FormItem = Form.Item;
const {RangePicker} = DatePicker;

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

interface BasicFormProps {
  submitting: boolean;
  dispatch: boolean;
}

interface CenterState {
  value: undefined,
  previewVisible: boolean,
  previewImage: '',
  previewTitle: '',
  fileList: any
}

// class New extends React.Component {

class NewPage extends React.Component<BasicFormProps, CenterState> {

  props: BasicFormProps = {
    submitting: false,
    dispatch: false
  }
  state: CenterState = {
    value: undefined,
    previewVisible: false,
    previewImage: '',
    previewTitle: '',
    fileList: [
      {
        uid: '-1',
        name: 'image.png',
        status: 'done',
        url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
      },
      {
        uid: '-2',
        name: 'image.png',
        status: 'done',
        url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
      },
      {
        uid: '-3',
        name: 'image.png',
        status: 'done',
        url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
      },
      {
        uid: '-4',
        name: 'image.png',
        status: 'done',
        url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
      },
      {
        uid: '-xxx',
        percent: 50,
        name: 'image.png',
        status: 'uploading',
        url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
      },
      {
        uid: '-5',
        name: 'image.png',
        status: 'error',
      }
    ]
  };
  //const { fileList } = this.state;
  handlePreview = async file => {
  if (!file.url && !file.preview) {
    file.preview = await getBase64(file.originFileObj);
  }

  // @ts-ignore
  this.setState({
    previewImage: file.url || file.preview,
    previewVisible: true,
    previewTitle: file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
  });


  handleChange = () => this.setState({fileList});
  handleCancel = () => this.setState({previewVisible: false});


  const uploadButton = (
    <div>
      <PlusOutlined/>
      <div style={{marginTop: 8}}>Upload</div>
    </div>
  );

//const setShowPublicUsers = React.useState(false);
  const formItemLayout = {
    labelCol: {
      xs: {span: 24},
      sm: {span: 7},
    },
    wrapperCol: {
      xs: {span: 24},
      sm: {span: 12},
      md: {span: 10},
    },
  };
  onFinish = (values: { [key: string]: any }) => {
    const {dispatch} = this.props;
    dispatch({
      type: 'formAndbasicForm/submitRegularForm',
      payload: values,
    });
  };
  onFinishFailed = (errorInfo: any) => {
    // eslint-disable-next-line no-console
    console.log('Failed:', errorInfo);
  };

  onValuesChange = (changedValues: { [key: string]: any }) => {
    const {publicType} = changedValues;
    if (publicType) {
      // setShowPublicUsers(publicType === '2');
    }

  };
  onChange = value => {
    console.log(value);
    this.setState({value});
  };

  render()
  {
    return (
      <PageContainer content={<FormattedMessage id="form.new.desc"/>}>
        <Card bordered={false}>
          <Form
            hideRequiredMark
            style={{marginTop: 8}}
            form={form}
            name="basic"
            initialValues={{public: '1'}}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed(0)}
            onValuesChange={onValuesChange}
          >
            <FormItem
              {...formItemLayout}
              label={<FormattedMessage id="form.new.newcourse.coursename.label"/>}
              name="publicType"
              rules={[
                {
                  required: true,
                  message: formatMessage({id: 'formandbasic-form.title.required'}),
                },
              ]}
            >
              <Input placeholder={formatMessage({id: 'form.new.newcourse.coursename.placeholder'})}/>
            </FormItem>
            <FormItem
              {...formItemLayout}
              label={<FormattedMessage id="form.new.newcourse.author.label"/>}
              name="publicType"
              rules={[
                {
                  required: true,
                  message: formatMessage({id: 'formandbasic-form.title.required'}),
                },
              ]}
            >
              <Input placeholder={formatMessage({id: 'form.new.newcourse.author.placeholder'})}/>
            </FormItem>
            <FormItem
              {...formItemLayout}
              label={<FormattedMessage id="formandbasic-form.date.label"/>}
              name="date"
              rules={[
                {
                  required: true,
                  message: formatMessage({id: 'formandbasic-form.date.required'}),
                },
              ]}
            >
              <RangePicker
                style={{width: '100%'}}
                placeholder={[
                  formatMessage({id: 'formandbasic-form.placeholder.start'}),
                  formatMessage({id: 'formandbasic-form.placeholder.end'}),
                ]}
              />
            </FormItem>
            <FormItem
              {...formItemLayout}
              label="课程分类"
              name="payAccount"
              rules={[{required: true, message: '请选择付款账户'}]}
            >
              <Select placeholder="test@example.com">
                <Select.Option value="ant-design@alipay.com">ant-design@alipay.com</Select.Option>
              </Select>
            </FormItem>
            <FormItem
              {...formItemLayout}
              label="课程分类"
              name="payAccount2"
              rules={[{required: true, message: '请选择付款账户'}]}
            >
              <TreeSelect
                style={{width: '100%'}}
                value={state.value}
                dropdownStyle={{maxHeight: 400, overflow: 'auto'}}
                treeData={treeData}
                placeholder="Please select"
                treeDefaultExpandAll
                onChange={this.onChange}
              />
            </FormItem>
            <FormItem
              {...formItemLayout}
              label="课程封面"
              name="payAccount2"
              rules={[{required: true, message: '请选择付款账户'}]}
            >
              <Upload
                action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                listType="picture-card"
                fileList={fileList}
                onPreview={this.handlePreview}
                onChange={this.handleChange}
              >
                {fileList.length >= 8 ? null : uploadButton}
              </Upload>
              <Modal
                visible={previewVisible}
                title={previewTitle}
                footer={null}
                onCancel={this.handleCancel}
              >
                <img alt="example" style={{width: '100%'}} src={previewImage}/>
              </Modal>
            </FormItem>
          </Form>
        </Card>
      </PageContainer>
    )
  }
};
  export default connect(({ loading }: { loading: { effects: { [key: string]: boolean } } }) => ({
  submitting: loading.effects['formAndbasicForm/submitRegularForm'],
}))(NewPage);
